const TOKEN_KEY = "sweet-life-token";
const THEME_KEY = "sweet-life-theme";
const PROFILE_CACHE_KEY = "sweet-life-profile";

const formMessage = document.getElementById("formMessage");
const loginForm = document.getElementById("loginForm");
const registerForm = document.getElementById("registerForm");
const showRegisterLink = document.getElementById("showRegister");
const showLoginLink = document.getElementById("showLogin");

function showMessage(text, type = "info") {
  if (!formMessage) return;
  if (!text) {
    formMessage.textContent = "";
    formMessage.classList.remove("show", "error", "success");
    return;
  }
  formMessage.textContent = text;
  formMessage.classList.remove("error", "success");
  if (type === "error") {
    formMessage.classList.add("error");
  } else if (type === "success") {
    formMessage.classList.add("success");
  }
  formMessage.classList.add("show");
}

function toggleForms(showRegister) {
  if (showRegister) {
    loginForm.classList.add("hidden");
    registerForm.classList.remove("hidden");
  } else {
    registerForm.classList.add("hidden");
    loginForm.classList.remove("hidden");
  }
  showMessage("");
}

async function requestJson(url, payload) {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(payload),
  });

  let data;
  try {
    data = await response.json();
  } catch (error) {
    throw new Error("\u670d\u52a1\u5668\u6ca1\u6709\u8fd4\u56de\u6709\u6548\u6570\u636e");
  }

  if (!response.ok || data.success === false) {
    throw new Error(data.message || "\u8bf7\u6c42\u5931\u8d25\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5");
  }
  return data;
}

async function handleLogin(event) {
  event.preventDefault();
  showMessage("\u6b63\u5728\u767b\u5f55\uff0c\u8bf7\u7a0d\u5019...");
  const payload = {
    username: loginForm.username.value.trim(),
    password: loginForm.password.value,
  };
  try {
    const result = await requestJson("/api/auth/login", payload);
    const token = result.data?.token;
    if (!token) {
      throw new Error("\u767b\u5f55\u54cd\u5e94\u7f3a\u5c11\u4ee4\u724c\u4fe1\u606f");
    }
    localStorage.setItem(TOKEN_KEY, token);
    const theme = result.data?.user?.themePreference || result.data?.dashboard?.themePreference;
    if (theme) {
      localStorage.setItem(THEME_KEY, theme);
    }
    if (result.data?.dashboard) {
      localStorage.setItem(PROFILE_CACHE_KEY, JSON.stringify(result.data.dashboard));
    }
    showMessage("\u767b\u5f55\u6210\u529f\uff0c\u6b63\u5728\u8fdb\u5165\u751c\u871c\u7a7a\u95f4...", "success");
    setTimeout(() => {
      window.location.href = "app.html";
    }, 400);
  } catch (error) {
    showMessage(error.message || "\u767b\u5f55\u5931\u8d25\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5", "error");
  }
}

async function handleRegister(event) {
  event.preventDefault();
  const username = registerForm.username.value.trim();
  const displayName = registerForm.displayName.value.trim();
  const email = registerForm.email.value.trim();
  const password = registerForm.password.value;
  const confirmPassword = registerForm.confirmPassword.value;

  if (password !== confirmPassword) {
    showMessage("\u4e24\u6b21\u8f93\u5165\u7684\u5bc6\u7801\u4e0d\u4e00\u81f4\uff0c\u8bf7\u91cd\u65b0\u786e\u8ba4", "error");
    return;
  }

  showMessage("\u6b63\u5728\u63d0\u4ea4\u6ce8\u518c\u4fe1\u606f...");
  const payload = { username, displayName, email, password };
  try {
    await requestJson("/api/auth/register", payload);
    showMessage("\u6ce8\u518c\u6210\u529f\uff0c\u8bf7\u4f7f\u7528\u65b0\u8d26\u53f7\u767b\u5f55", "success");
    registerForm.reset();
    toggleForms(false);
  } catch (error) {
    showMessage(error.message || "\u6ce8\u518c\u5931\u8d25\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5", "error");
  }
}

function restoreSession() {
  const token = localStorage.getItem(TOKEN_KEY);
  if (token) {
    window.location.href = "app.html";
  }
}

document.addEventListener("DOMContentLoaded", () => {
  restoreSession();
  loginForm.addEventListener("submit", handleLogin);
  registerForm.addEventListener("submit", handleRegister);
  showRegisterLink.addEventListener("click", () => toggleForms(true));
  showLoginLink.addEventListener("click", () => toggleForms(false));
});
